package com.hujiang.hummer.xmpp;

import java.security.InvalidParameterException;

public class BareJID implements Comparable<BareJID> {

	private final String _domain;
	private final String _name;
	private final String _to_string;
	private final int _hashcode;
	
	private BareJID(String name, String domain) {
		
		this._name = name;
		this._domain = domain;
		this._to_string = toString(name, domain);
		this._hashcode = this._to_string.toLowerCase().hashCode();
	}
	
	public static String toString(String name, String domain) {
		
		return (name != null && name.length() > 0) ? name + "@" + domain : domain;
	}
	
	public static BareJID newInstance(String name, String domain) {
		
		if (name == null || name.length() < 1) {
			throw new InvalidParameterException("invalid jid's name");
		}
		
		if (domain == null || domain.length() < 1) {
			throw new InvalidParameterException("invalid jid's domain");
		}
		
		return new BareJID(name, domain);
	}
	
	public String get_domain() {
		return _domain;
	}
	
	public String get_name() {
		return _name;
	}
	
	@Override
	public String toString() {
		
		return this._to_string;
	};
	
	@Override
	public int hashCode() {
		
		return this._hashcode;
	};
	
	@Override
	public int compareTo(BareJID other) {

		return this._to_string.compareToIgnoreCase(other._to_string);
	}

	@Override
	public boolean equals(Object obj) {

		boolean result = false;
		
		if (obj instanceof BareJID) {
			
			result = this.compareTo((BareJID)obj) == 0;
		}
		
		return result;
	}

	public static String[] parseJID(String jid) {
		
		String[] result = new String[3];
		
		if (jid != null && jid.length() > 0) {
			
			int idx = jid.indexOf('/');
			result[2] = idx == -1 ? null : jid.substring(idx + 1);
			
			String bareJid = idx == -1 ? jid : jid.substring(0, idx);
			
			idx = bareJid.indexOf('@');
			result[0] = idx == -1 ? null : bareJid.substring(0, idx);
			result[1] = idx == -1 ? bareJid : bareJid.substring(idx + 1);
		}
		
		return result;
	}
}
